package com.tedu.springmvc2.controller;

import com.tedu.springmvc2.mapper.UserMapper;
import com.tedu.springmvc2.pojo.dto.UserDTO;
import com.tedu.springmvc2.pojo.dto.UserUpdateDTO;
import com.tedu.springmvc2.pojo.entity.User;
import com.tedu.springmvc2.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * RESTful风格
 * 根据请求方式区分操作，地址上不添加动词
 * GET:主要是获取某个资源
 * POST:在服务端新建一个资源
 * PUT:修改服务器上某个资源
 * DELETE：删除服务器上某个资源
 *
 */

/*
 * 可以将每个处理请求中相同地址路径部分提炼出来,放在Controller类上使用
 * @RequestMapping注解
 * */
@RestController
@RequestMapping("users")
public class RestfulUserController {
    @Autowired
    private UserMapper userMapper;
    /*
    * 注册用户:在服务器上新建一个资源(数据)
    * POST/users
    * */

    //@RequestMapping(value = "/users", method = RequestMethod.POST)
    @PostMapping

    public String add(UserDTO userDTO){
        System.out.println("开始注册用户");
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        userMapper.insertUser(user);
        return "注册成功";
    }

    //@RequestMapping(value = "/users", method = RequestMethod.PUT)
    @PutMapping
    public String update(UserUpdateDTO userDTO){
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        System.out.println();
        user.setCreated(new Date());
        int num = userMapper.updateById(user);
        return num>0 ? "修改成功":"修改失败";
    }

    //@RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        int num = userMapper.deleteById(id);
        return num>0 ? "删除成功":"删除失败";
    }

    //@RequestMapping(value = "/users", method = RequestMethod.GET)
    //@GetMapping("/users")
    @GetMapping
    public List<UserVO> findById(){
        return userMapper.selectAll();
    }

    /*@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
    public UserVO findById(@PathVariable Integer id){
        List<UserVO> list = userMapper.selectAll();
        return list.get(id);
    }*/

    //@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
    //@GetMapping("/users/{id}")
    @GetMapping("/{id}")
    public UserVO selectById(@PathVariable Integer id){
        return userMapper.selectById(id);
    }
}
